package com.eco.fanliapp.utils;

/**
* @description: excel导出工具
* @author: sunhx
* @date: 2018/8/17
*/

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;

public class ExportExcelUtil {
    private final static Logger LOGGER = LoggerFactory.getLogger(ExportExcelUtil.class);


    /**
     * 导出Excel方法
     * @param response HttpServletResponse
     * @param fileName 文件名称
     * @param sheetName sheet名称
     * @param title 标题
     * @param values 内容
     * @param wb HSSFWorkbook对象
     */
    public static void exportExcel(HttpServletResponse response,String fileName,
                                     String sheetName,String []title,String [][]values, SXSSFWorkbook wb){


        // 第一步，创建一个HSSFWorkbook，对应一个Excel文件
        if(wb == null){
            wb = new SXSSFWorkbook();
        }

        // 第二步，在workbook中添加一个sheet,对应Excel文件中的sheet
        Sheet sheet = wb.createSheet(sheetName);

        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
        Row row = sheet.createRow(0);


        //声明列对象
        Cell cell = null;

        //创建标题
        for(int i=0;i<title.length;i++){
            cell = row.createCell(i);
            cell.setCellValue(title[i]);
        }

        //创建内容
        for(int i=0;i<values.length;i++){
            row = sheet.createRow(i + 1);
            for(int j=0;j<values[i].length;j++){
                //将内容按顺序赋给对应的列对象
                row.createCell(j).setCellValue(values[i][j]);
            }
        }

        //响应到客户端
        try {
            response.setHeader("Content-Disposition", "attachment;filename=\""+ new String(fileName.getBytes("gbk"), "ISO8859-1")+ ".xlsx" + "\"" );
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");

            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            LOGGER.debug(e.toString());
        }

    }


}
